package breeze.pixel.weather.apps_util.utils.appsettings;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.provider.Settings;
import android.view.MenuItem;
import android.view.View;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.preference.ListPreference;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.SwitchPreference;

import java.io.File;
import java.util.Objects;

import breeze.pixel.weather.R;
import breeze.pixel.weather.apps_util.utils.AppToolUtil;
import breeze.pixel.weather.apps_util.utils.MDialog;
import breeze.pixel.weather.apps_util.utils.MToast;
import breeze.pixel.weather.service.app_widget.WeatherUtils;
import brz.breeze.app_utils.BAppUtils;
import brz.breeze.tool_utils.Blog;
import io.reactivex.annotations.NonNull;
import top.defaults.colorpicker.ColorPickerPopup;

public class SettingsView extends AppCompatActivity {

    public static AppSettings sets;

    @SuppressLint("StaticFieldLeak")
    public static Context context;

    @SuppressLint("StaticFieldLeak")
    public static SettingsView activity;

    static boolean saveBingPicIsSuccess = false;

    private Blog Blog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings_activity);
        if (savedInstanceState == null) {
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.settings, new SettingsFragment())
                    .commit();
        }
        Blog = new Blog(this);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        getWindow().setStatusBarColor(Color.parseColor("#f5f5f5"));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        init();
    }

    private void init() {
        context = this;
        activity = this;
        sets = AppSettings.getInstance(this);
    }

    public static boolean saveBingPic(Context context) {
        BAppUtils.execute(() -> {
            try {
                if (ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                    String path = AppToolUtil.getPicturePath() + AppToolUtil.getSimpleDate("yyyy_MM_dd HH-mm-ss") + ".jpg";
                    File file = new File(path);
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    Bitmap bitmap = AppToolUtil.getBingPic(context);
                    AppToolUtil.savePicture(context, bitmap, path);
                    saveBingPicIsSuccess = true;
                } else {
                    ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
                }
            } catch (Exception e) {
                brz.breeze.tool_utils.Blog.e(SettingsView.class.getSimpleName(), e.toString());
                saveBingPicIsSuccess = false;
            }
        });
        return saveBingPicIsSuccess;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 0) {
            if (saveBingPic(context)) {
                MToast.show(context, "保存成功!");
            } else {
                MToast.show(context, "保存失败！");
            }
        }
    }

    public static class SettingsFragment extends PreferenceFragmentCompat {

        private CharSequence[] list_keys_datas;

        @Override
        public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
            setPreferencesFromResource(R.xml.app_settings, rootKey);
            init();
        }

        private void init() {
            if (sets == null) {
                sets = AppSettings.getInstance(context);
            }
            SwitchPreference settings_hide_extra_data = findPreference("settings_hide_extra_data");
            if (settings_hide_extra_data != null) {
                settings_hide_extra_data.setChecked(sets.isHideExtraData());
            }
            MOnPreferenceChangeListener listener = new MOnPreferenceChangeListener();
            MOnPreferneceClickListener onPreferneceClickListener = new MOnPreferneceClickListener();
            ListPreference listPreference_keys = findPreference("list_keys");
            if (listPreference_keys != null) {
                list_keys_datas = listPreference_keys.getEntries();
                if (listPreference_keys.getEntries() == null) {
                    listPreference_keys.setValueIndex(0);
                }
                listPreference_keys.setSummary("当前线路：" + listPreference_keys.getEntry());
                listPreference_keys.setOnPreferenceChangeListener(listener);
            }
            Preference preference = findPreference("save_bing_pic");
            if (preference != null) {
                preference.setOnPreferenceClickListener(onPreferneceClickListener);
            }
            Preference deleteBingPic = findPreference("delete_bing_pic");
            if (deleteBingPic != null) {
                deleteBingPic.setOnPreferenceClickListener(onPreferneceClickListener);
            }
            SwitchPreference autoGetLocation = findPreference("auto_getlocation");
            if (autoGetLocation != null) {
                autoGetLocation.setChecked(sets.isAutoGetLocation());
                autoGetLocation.setOnPreferenceChangeListener(listener);
            }
            SwitchPreference checkNewVersion = findPreference("auto_check_newversion");
            if (checkNewVersion != null) {
                checkNewVersion.setChecked(sets.getCheckNewVersion());
                checkNewVersion.setOnPreferenceChangeListener(listener);
            }
            SwitchPreference auto_save_task = findPreference("auto_save_task");
            if (auto_save_task != null) {
                auto_save_task.setChecked(sets.isAutoSaveTaskInPanel());
            }
            Preference widget_textcolor = findPreference("widget_textcolor");
            Objects.requireNonNull(widget_textcolor).setOnPreferenceClickListener(onPreferneceClickListener);
            SwitchPreference hotFix = findPreference("hotFix");
            Objects.requireNonNull(hotFix).setChecked(sets.isHotFix());
        }

        class MOnPreferenceChangeListener implements Preference.OnPreferenceChangeListener {
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                switch (preference.getKey()) {
                    case "list_keys":
                        ListPreference preference1 = (ListPreference) preference;
                        int index = preference1.findIndexOfValue((String) newValue);
                        preference1.setSummary("当前线路:" + list_keys_datas[index]);
                        sets.setDefaultKey(index);
                        AppToolUtil.sendBroadcast(context, AppSettings._ACTION_UPDATE_DEFAULT_HEWEATHER_KEY);
                        break;
                    case "auto_getlocation":
                        sets.setAutoGetLocation((boolean) newValue);
                        AppToolUtil.sendBroadcast(context, AppSettings._ACTION_UPDATE_GET_CITY_METHOD);
                        break;
                    case "auto_check_newversion":
                        sets.setCheckNewVersion((boolean) newValue);
                        break;
                    case "ignore_battery_kill":
                        PowerManager manager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            boolean hasIgnored = manager.isIgnoringBatteryOptimizations(context.getPackageName());
                            if (!hasIgnored) {
                                @SuppressLint("BatteryLife") Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
                                intent.setData(Uri.parse("package:" + context.getPackageName()));
                                if (intent.resolveActivity(context.getPackageManager()) != null) {
                                    startActivity(intent);
                                } else {
                                    MToast.show(context, "开启失败！");
                                }
                            }
                        } else {
                            MToast.show(context, "安卓6.0以上才有用噢");
                        }
                        break;
                }
                return true;
            }
        }

        static class MOnPreferneceClickListener implements Preference.OnPreferenceClickListener {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                switch (preference.getKey()) {
                    case "save_bing_pic":
                        if (saveBingPic(context)) {
                            MToast.show(context, "保存成功!");
                        } else {
                            MToast.show(context, "保存失败！");
                        }
                        break;
                    case "delete_bing_pic":
                        MDialog dialog = new MDialog(context);
                        dialog.setTitle("提示");
                        dialog.setMessage("确定删除所保存的全部图片吗？");
                        dialog.setPositiveButton("确定", () -> {
                            String path = AppToolUtil.getPicturePath();
                            String[] files = new File(path).list();
                            if (files != null && files.length == 0) {
                                MToast.show(context, "没有发现图片噢");
                            } else if (files != null) {
                                for (String file : files) {
                                    String realpath = path + file;
                                    new File(realpath).delete();
                                }
                                MToast.show(context, "删除成功");
                            }
                        });
                        dialog.setNegativeBotton("取消", null);
                        dialog.show();
                        break;
                    case "widget_textcolor":
                        new ColorPickerPopup.Builder(context)
                                .initialColor(sets.getAppwidgetTextColor())
                                .enableAlpha(true)
                                .okTitle("确定")
                                .cancelTitle("取消")
                                .showIndicator(true)
                                .build()
                                .show(activity.getWindow().getDecorView(), new ColorPickerPopup.ColorPickerObserver() {
                                    @Override
                                    public void onColorPicked(int color) {
                                        sets.setAppwidgetTextColor(color);
                                        WeatherUtils.getData();
                                    }
                                });
                        break;
                }
                return true;
            }
        }
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }
}